<script setup lang="ts">
import { ref, watch } from 'vue'
import { useAuthStore } from '@/store/modules/auth'

const emit = defineEmits<{
  (e: 'success'): void
  (e: 'switch-to-login'): void
  (e: 'close-all'): void
}>()

const authStore = useAuthStore()
const form = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  nickName: '',
  phonenumber: '',
})
const error = ref('')
const loading = ref(false)
const usernameError = ref('')
const validating = ref(false)

let usernameTimeout: NodeJS.Timeout | null = null

const validateUsername = async () => {
  if (!form.value.username) {
    usernameError.value = '用户名不能为空'
    return
  }

  if (form.value.username.length < 3) {
    usernameError.value = '用户名至少需要3个字符'
    return
  }

  try {
    validating.value = true
    const exists = await authStore.checkUserNameExists(form.value.username)
    if (exists) {
      usernameError.value = '该用户名已被使用'
    } else {
      usernameError.value = ''
    }
  } catch (err: any) {
    usernameError.value = err.response?.data?.msg || '验证用户名时出错'
  } finally {
    validating.value = false
  }
}

watch(
  () => form.value.username,
  (newValue) => {
    if (usernameTimeout) {
      clearTimeout(usernameTimeout)
    }
    if (newValue) {
      usernameTimeout = setTimeout(validateUsername, 500)
    }
  },
)

const handleSubmit = async () => {
  if (usernameError.value) {
    error.value = '请修正用户名错误'
    return
  }

  if (!form.value.username || !form.value.email || !form.value.password || !form.value.nickName) {
    error.value = '请填写所有必填字段'
    return
  }

  if (form.value.password !== form.value.confirmPassword) {
    error.value = '两次输入的密码不一致'
    return
  }

  try {
    loading.value = true
    await authStore.register({
      userName: form.value.username,
      email: form.value.email,
      password: form.value.password,
      nickName: form.value.nickName,
      phonenumber: form.value.phonenumber || undefined,
    })
    emit('close-all')
    setTimeout(() => {
      window.location.href = '/'
    }, 100)
  } catch (err: any) {
    error.value = err.response?.data?.message || '注册失败，请重试'
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <form @submit.prevent="handleSubmit" class="auth-form">
    <div class="form-group">
      <label for="username">用户名</label>
      <input
        id="username"
        v-model="form.username"
        type="text"
        required
        placeholder="请输入用户名"
        @blur="validateUsername"
        :class="{ error: usernameError }"
      />
      <span v-if="validating" class="validating-message">正在验证...</span>
      <span v-else-if="usernameError" class="error-message">{{ usernameError }}</span>
    </div>

    <div class="form-group">
      <label for="nickName">昵称</label>
      <input id="nickName" v-model="form.nickName" type="text" required placeholder="请输入昵称" />
    </div>

    <div class="form-group">
      <label for="email">邮箱</label>
      <input id="email" v-model="form.email" type="email" required placeholder="请输入邮箱" />
    </div>

    <div class="form-group">
      <label for="phonenumber">手机号</label>
      <input
        id="phonenumber"
        v-model="form.phonenumber"
        type="tel"
        placeholder="请输入手机号（选填）"
        pattern="[0-9]{11}"
      />
    </div>

    <div class="form-group">
      <label for="password">密码</label>
      <input
        id="password"
        v-model="form.password"
        type="password"
        required
        placeholder="请输入密码"
      />
    </div>

    <div class="form-group">
      <label for="confirmPassword">确认密码</label>
      <input
        id="confirmPassword"
        v-model="form.confirmPassword"
        type="password"
        required
        placeholder="请再次输入密码"
      />
    </div>

    <div v-if="error" class="error-message">{{ error }}</div>

    <button type="submit" :disabled="loading" class="submit-button">
      {{ loading ? '注册中...' : '注册' }}
    </button>

    <div class="login-link">
      已有账号？
      <a href="#" @click.prevent="emit('switch-to-login')">立即登录</a>
    </div>
  </form>
</template>

<style scoped lang="scss">
.auth-form {
  .form-group {
    margin-bottom: 1rem;

    label {
      display: block;
      margin-bottom: 0.5rem;
      color: #4b5563;
      font-weight: 500;
    }

    input {
      width: 100%;
      padding: 0.75rem;
      border: 1px solid #d1d5db;
      border-radius: 6px;
      font-size: 1rem;

      &:focus {
        outline: none;
        border-color: #6366f1;
        box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
      }
    }

    input.error {
      border-color: #dc2626;
    }

    .validating-message {
      font-size: 0.875rem;
      color: #6366f1;
      margin-top: 0.25rem;
    }

    .error-message {
      font-size: 0.875rem;
      color: #dc2626;
      margin-top: 0.25rem;
    }
  }
}

.error-message {
  color: #dc2626;
  margin-bottom: 1rem;
  padding: 0.5rem;
  background-color: #fef2f2;
  border-radius: 4px;
  font-size: 0.9rem;
}

.submit-button {
  width: 100%;
  padding: 0.75rem;
  background-color: #6366f1;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;

  &:hover {
    background-color: #4f46e5;
  }

  &:disabled {
    background-color: #9ca3af;
    cursor: not-allowed;
  }
}
</style>
